﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data;
using System.Data.SqlClient;
using System.Data.Common;
/// <summary>
/// Class to handle SQL exception, so other classes don't have to
/// </summary>
namespace DBLayer
{
    public class SqlUtility
    {
        public SqlUtility()
        {
          
        }
        //Insert Data in database, handels Sql error
        public int ExecuteData(SqlCommand _cmd, SqlConnection _con)
        {
            int result = -1;
            SqlTransaction transaction = null;
 
                transaction = _con.BeginTransaction();
                _cmd.Transaction = transaction;
            
            try
            {
                int i = _cmd.ExecuteNonQuery();
                if (i > 0)
                {
                    result = 1;
                }
                else
                {
                    result = -1;
                }
                transaction.Commit();
            }
            catch (SqlException ex)
            {
                transaction.Rollback();
                result = -1;
                System.Console.WriteLine("Fejl: " + ex.Message);
            }
            _con.Close();
            _con.Dispose();
            return result;
        }
        //Insert data that requires more than one SQL command
        public int ExecuteMultipleData(SqlCommand _cmd, SqlCommand _cmd2, SqlConnection _con)
        {
            int result = -1;
            SqlTransaction transaction = null;


                transaction = _con.BeginTransaction();
                _cmd.Transaction = transaction;
                _cmd2.Transaction = transaction;
            
            try
            {
                int i = _cmd.ExecuteNonQuery();
                int j = _cmd2.ExecuteNonQuery();
                if (i > 0 && j > 0)
                {
                    result = 1;
                }
                else
                {
                    result = -1;
                }
                transaction.Commit();
            }
            catch (SqlException ex)
            {
                result = -1;
                transaction.Rollback();
                System.Console.WriteLine("Fejl: " + ex.Message);
            }
            _con.Close();
            _con.Dispose();
            return result;
        }
        public SqlConnection GetCon()
        {
            SqlConnection connect = new SqlConnection("Data Source=balder.ucn.dk;Initial Catalog=dmaa0912_E2;Persist Security Info=True;User ID=DMaa0912_e2;Password=MaaGodt");
            return connect;
        }
    }
}
